<template>
  <div class="app-container">

    <u-page title="订单管理">

      <u-filtered>
        <el-form :inline="true" :model="listQuery" class="search-form">
          <el-form-item label="批次号" prop="批次号">
            <el-input v-model="listQuery.no" placeholder="请输入批次号" clearable style="width: 200px"/>
          </el-form-item>
          <el-form-item label="专柜号" prop="chanlCode">
            <el-input v-model="listQuery.chanlCode" placeholder="请输入专柜号" clearable style="width: 200px"/>
          </el-form-item>
          <el-form-item label="导购姓名" prop="guideName">
            <el-input v-model="listQuery.guideName" placeholder="请输入导购姓名" clearable style="width: 200px"/>
          </el-form-item>
          <el-form-item label="导购手机" prop="guideMobile">
            <el-input v-model="listQuery.guideMobile" placeholder="请输入导购手机" clearable style="width: 200px"/>
          </el-form-item>
          <el-form-item label="开单时间">
            <u-date-time-picker v-model="searchDate" value-format="yyyy-MM-dd HH:mm:ss" @change="changeSearchDate"/>
          </el-form-item>
          <el-form-item label="交易状态" prop="status">
            <el-select v-model="listQuery.status" placeholder="请选择交易状态" class="status" clearable>
              <el-option label="全部" value=""/>
              <el-option label="进行中" :value="-1"/>
              <el-option label="已结束" :value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="hdlFilter">搜索</el-button>
            <el-button type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
          </el-form-item>
        </el-form>
      </u-filtered>

      <u-table
        index="index"
        :data="list"
        :loading="listLoading"
        :options="listOptions"
        :columns="columns"
        :pagination.sync="listQuery"
        :fetch="hdlList"
        @selection-change="hdlSelectChange"
      >
        <template v-slot:right>
          <el-table-column label="操作" align="center" fixed="right" width="200">
            <template slot-scope="{ row }">
              <el-button type="text" @click="hdlEdit(row)">详情</el-button>
              <el-button type="text" @click="jumpOrder(row)">订单明细</el-button>
            </template>
          </el-table-column>
        </template>
      </u-table>
    </u-page>

    <!-- 订单信息 -->
    <u-dialog title="批次信息" :show.sync="dialogFormVisible" :footer="false" @confirm="hdlUpdate()">
      <el-form ref="dialogForm" :rules="rules" :model="dataForm" label-position="top" label-width="80px">

        <el-descriptions :column="2" border style="margin-bottom: 10px">
          <el-descriptions-item label="批次号">{{ dataForm.no }}</el-descriptions-item>

          <el-descriptions-item label="导购姓名">{{ dataForm.guideName }}</el-descriptions-item>
          <el-descriptions-item label="导购手机">{{ dataForm.guideMobile }}</el-descriptions-item>

          <el-descriptions-item label="开单时间">{{ dataForm.createTime }}</el-descriptions-item>
          <el-descriptions-item label="活动时间">{{ (dataForm.startTime) }} ~ {{ dataForm.endTime }}
          </el-descriptions-item>
          <el-descriptions-item label="开单名额">{{ (dataForm.num) }}</el-descriptions-item>
          <el-descriptions-item label="提货方式">
            <el-tag v-if="dataForm.deliveryMethod === 1" type="info">自提</el-tag>
            <el-tag v-if="dataForm.deliveryMethod === 2" type="info">寄递</el-tag>
            <el-tag v-if="dataForm.deliveryMethod === 3" type="info">自提及寄递</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="单笔总价">
            <el-tag type="success">¥ {{ dataForm.amount }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="交易状态">
            <el-tag v-if="dataForm.status === -1" type="info">已关闭</el-tag>
            <el-tag v-if="dataForm.status === 0" type="danger">待付款</el-tag>
            <el-tag v-if="dataForm.status === 1" type="success">已付款</el-tag>
            <el-tag v-if="dataForm.status ===2" type="danger">支付失败</el-tag>
            <el-tag v-if="dataForm.status === 3" type="success">已完成</el-tag>
            <el-tag v-if="dataForm.status === 4" type="success">已退款</el-tag>
            <el-tag v-if="dataForm.status === 5" type="danger">退款失败</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="备注" :span="2">{{ dataForm.note }}</el-descriptions-item>

        </el-descriptions>

        <div style="margin: 10px 0; font-weight: 600;">厂商信息</div>
        <el-descriptions :column="2" title="" border>
          <el-descriptions-item label="商户号" :span="2">{{ dataForm.merchantNo }}</el-descriptions-item>
          <el-descriptions-item label="商户名称" :span="2">{{ dataForm.merchantName }}</el-descriptions-item>
        </el-descriptions>

        <div style="margin: 10px 0; font-weight: 600;">商品列表</div>
          <el-table :data="dataForm.goodsList" border size="small" :header-cell-style="{backgroundColor: '#fafafa'}">
            <el-table-column label="商品名称" prop="goodsName"/>
            <el-table-column label="商品编码" prop="goodsId"/>
            <el-table-column label="商品条码" prop="barCode"/>
            <el-table-column label="商品单价/元" prop="unitPrice"/>
            <el-table-column label="数量" prop="num"/>
            <el-table-column label="商品合计/元" prop="z_amount"/>
          </el-table>
      </el-form>
    </u-dialog>

    <u-dialog title="上报数据" :show.sync="jsonDialogVisible" :footer="false" width="45%" class="code">
      <el-input v-model="detailJson" autosize type="textarea" disabled placeholder="{}"/>
    </u-dialog>

    <!-- 退款申请 -->
    <u-dialog title="订单退款申请" :show.sync="dialogRefundFormVisible" @confirm="hdlRefundApply()">
      <el-form ref="dataRefundForm" :rules="refundRules" :model="dataRefundForm" label-width="80px">

        <el-descriptions :column="2" border style="margin-bottom: 10px">
          <el-descriptions-item label="订单号">{{ dataRefundForm.orderNo }}</el-descriptions-item>


          <el-descriptions-item label="交易时间">{{ dataRefundForm.createTime }}</el-descriptions-item>

          <el-descriptions-item label="交易状态">
            <el-tag v-if="dataRefundForm.status === -1" type="info">已关闭</el-tag>
            <el-tag v-if="dataRefundForm.status === 3" type="success">已完成</el-tag>
            <el-tag v-if="dataRefundForm.status === 0" type="danger">待付款</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="支付时间">
            <div v-if="dataRefundForm.payTime">
              {{ dataRefundForm.payTime }}
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="流水号">
            <div v-if="dataRefundForm.tradeNo">
              {{ dataRefundForm.tradeNo }}
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="总金额/元">
            {{ $u.amount.F2Y(dataRefundForm.totalFee) }}
          </el-descriptions-item>

          <el-descriptions-item label="优惠金额/元">
            {{ $u.amount.F2Y(dataRefundForm.discFee) }}
          </el-descriptions-item>

          <el-descriptions-item label="实付金额/元" :span="2">
            {{ $u.amount.F2Y(dataRefundForm.paidFee) }}
          </el-descriptions-item>

          <el-descriptions-item label="实付积分" :span="2">
            {{ dataRefundForm.payPoints }}
          </el-descriptions-item>

          <el-descriptions-item label="退款金额" :span="2">
            <el-form-item prop="refundType" label-width="auto">
              <el-radio-group v-model="dataRefundForm.refundType">
                <el-radio :label="0">
                  全额退款
                  <el-tooltip class="item" effect="dark" content="包含积分" placement="top">
                    <i class="el-icon-question"/>
                  </el-tooltip>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-descriptions-item>


          <el-descriptions-item label="备注" :span="2">
            <el-form-item prop="remark" label-width="auto">
              <el-input v-model="dataRefundForm.remark" type="textarea" placeholder="请输入备注以方便追溯历史原因(必填)"
                        clearable maxlength="200" show-word-limit/>
            </el-form-item>
          </el-descriptions-item>

        </el-descriptions>

      </el-form>
    </u-dialog>
  </div>
</template>
<script>

export default {
  components: {},
  data() {
    return {
      api: this.$u.api.PluginsScanshopQr,
      list: [],
      goodList: [],
      listLoading: false,
      listOptions: {
        index: true,
        mutiSelect: true,
        stripe: true
      },
      listQuery: {
        page: 1,
        pageSize: 10,
        totalCount: 1,
        beginTime: '',
        endTime: '',
        orderNo: '',
        tradeNo: '',
        ack: '',
        status: '',
        refundApplyState: ''
      },
      inputDateRange: [],
      // 表格
      columns: [
        {
          prop: 'no',
          label: '批次号',
          width: '166',
          render: (h, params) => {
            return h('el-tag', params.row.no)
          }
        },
        {
          prop: 'guideName',
          label: '导购姓名',
          width: '166',
          render: (h, params) => {
            return h('div', params.row.guideName)
          }
        },
        {
          prop: 'guideMobile',
          label: '导购手机',
          width: '166',
          render: (h, params) => {
            return h('div', params.row.guideMobile)
          }
        },
        {
          prop: 'createdAt',
          label: '开单时间',
          width: '166',
          sortable: true,
          timestamp: true
        },
        {
          prop: 'startTime',
          label: '活动时间',
          width: '180',
          render: (h, params) => {
            let {startTime, endTime} = params.row
            if (!startTime) {
              startTime = '不限制'
            }
            if (!endTime) {
              endTime = '不限制'
            }
            return [
              h('el-tag', {props: {effect: 'plain'}}, '起始:' + startTime),
              h('br'),
              h('el-tag', {props: {effect: 'plain'}}, '终止:' + endTime)
            ]
          }
        },
        {
          prop: 'paiNum',
          label: '已售/开单名额',
          width: '180',
          render: (h, params) => {
            let paidNum = params.row.paidNum
            let num = params.row.num
            if (!paidNum) paidNum=0
            if (!num) num=0
            return h('div', paidNum + '/' + num)
          }
        },
        {
          prop: 'status',
          label: '状态',
          render: (h, params) => {
            if (params.row.status) {
              return h('el-tag', {props: {type: 'success'}}, '进行中')
            } else {
              return h('el-tag', {props: {type: 'danger'}}, '已结束')
            }
          }
        }
      ],

      dialogFormVisible: false,
      dialogStatus: '',

      dataForm: {},
      rules: {
        note: [
          {required: true, message: '请输入备注信息', trigger: ['blur']}
        ]
      },
      jsonDialogVisible: false,
      detailJson: {},

      // 退款
      dialogRefundFormVisible: false,
      dataRefundForm: {
        refundType: 0
      },
      refundRules: {
        refundType: [
          {required: true, message: '请选择退款类型', trigger: ['blur']}
        ],
        note: [
          {required: true, message: '请输入备注信息', trigger: ['blur']}
        ]
      }
    }
  },
  created() {
    this.hdlList()
  },
  methods: {
    // 核销响应信息格式化
    formatCouponResult(item) {
      const json = JSON.parse(item)
      const data = {
        '交易号': json.tranNo,
        '优惠券消费详情': {
          '优惠券编号': '',
          '财务列表': {}
        }
      }
      json.couponConsumeDetail.forEach(coupon => {
        // '优惠券编号': coupon.couponNo,
        data.优惠券消费详情.优惠券编号 = coupon.couponNo
        coupon.financeList.forEach(item => {
          data.优惠券消费详情.财务列表 = {
            '账号': item.accountNo,
            '优惠券标题': item.accountTitle,
            '优先级': item.accountPriority,
            '金额': item.accountValue
          }
        })
      })
      console.log(data)
      return JSON.stringify(data)
    },
    // 数据格式化
    formatExtendInfo(item) {
      const json = JSON.parse(item)
      let formattedResult = {}
      if (typeof json === 'object') {
        formattedResult = {
          '订单号': json.orderNo,
          '车牌号': json.plateNo,
          '入场时间': json.entryTime,
          '支付时间': json.payTime,
          '停车时长(分)': json.elapsedTime,
          '停车时长': json.elapsed,
          '优惠券列表': json.couponList,
          '总费用': json.totalFee,
          '优惠费用': json.discFee,
          '实付费用': json.paidFee
        }
      } else {
        formattedResult = {
          '券号': json
        }
      }

      const data = []
      // 输出转换后的结果
      for (const [key, value] of Object.entries(formattedResult)) {
        const formattedData = `${key}: ${value}`
        data.push(formattedData)
      }
      return data
    },
    // 导出数据
    handleDownload() {
      // 复制值
      const list = this.$u.deepClone(this.list)
      // 业务数据处理
      list.forEach(item => {
        this.$set(item, 'status', item.status === 0 ? '代付款' : item.status === 1 ? '已关闭' : item.status === 3 ? '已完成' : item.status === 4 ? '已退款' : item.status === 5 ? '退款失败' : '')
        this.$set(item, 'totalFee', item.totalFee ? this.$u.amount.F2Y(item.totalFee) : '0')
        this.$set(item, 'discFee', item.discFee ? this.$u.amount.F2Y(item.discFee) : '0')
        this.$set(item, 'paidFee', item.paidFee ? this.$u.amount.F2Y(item.paidFee) : '0')
        this.$set(item, 'payType', item.payType === 21 ? '微信支付' : '')
        this.$set(item, 'fullRefund', item.fullRefund === 1 ? '是' : '否')
        this.$set(item, 'refundFee', item.refundFee ? this.$u.amount.F2Y(item.refundFee) : '')
        this.$set(item, 'discInfo', item.discInfo ? this.formatDiscInfo(item.discInfo) : '')
        this.$set(item, 'businessStatus', item.businessStatus === 1 ? '成功' : item.businessStatus === 2 ? '失败' : '')
        this.$set(item, 'ack', item.ack === 0 ? '待处理' : item.ack === 1 ? '成功' : item.ack === 2 ? '失败' : '')
        this.$set(item, 'rechargeState', item.rechargeState === 0 ? '充值中' : item.rechargeState === 1 ? '充值成功' : item.rechargeState === 2 ? '充值失败' : item.rechargeState === 5 ? '不需要充值' : '')
        this.$set(item, 'refundApplyState', item.refundApplyState === 0 ? '未申请' : item.refundApplyState === 1 ? '申请中' : item.refundApplyState === 2 ? '审核失败' : item.refundApplyState === 3 ? '审核通过' : '')
      })
      console.log(list)
      // 表头&表数据
      const tHeader = ['交易时间', '支付时间', '订单类型', '订单号', '交易流水号', 'openid', '会员卡号', '商品名称', '商品编码', '支付类型', '订单总金额', '优惠金额', '实付金额', '使用积分', '交易状态', '充值状态', '充值订单号', '充值成功时间', '上报数据', '上报失败原因', '退款订单号', '退款流水号', '是否全额退款', '退款金额', '退款时间', '退款失败原因', '退款状态', '退款申请人', '退款审核人', '订单备注']
      const filterVal = ['createTime', 'payTime', 'type', 'orderNo', 'tradeNo', 'openid', 'cardNo', 'goodsName', 'goodsNo', 'payType', 'totalFee', 'discFee', 'paidFee', 'payPoints', 'status', 'rechargeState', 'rechargeOrderNo', 'rechargeSuccessTime', 'ack', 'ackMsg', 'refundNo', 'refundChannelNo', 'fullRefund', 'refundFee', 'refundTime', 'refundMsg', 'refundApplyState', 'refundApplyUser', 'refundUser', 'note']
      const data = list.map(v => filterVal.map(j => {
        return v[j]
      }))
      this.$u.exports.excel('虚拟商品订单记录', tHeader, data)
    },
    // 查看传输内容
    orderDetailToJson(row) {
      const {body} = row
      const content = body ? JSON.parse(body) : {}
      console.log(content)
      this.detailJson = JSON.stringify(content, null, '\t')
      this.jsonDialogVisible = true
    },
    // 重试
    hdlRetryById(row) {
      const {id} = row
      const self = this
      self.$confirm('确定进行重传?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self.api.fetchByRetryId(id).then(() => {
          // 刷新数据列表
          self.hdlList()
          // 通知信息
          self.$u.msg('操作成功')
        })
      }).catch(() => {
      })
    },
    // 退款申请
    hdlOpenRefundApply(row) {
      const self = this
      // 初始化数据源
      self.dataRefundForm = Object.assign({refundType: 0, refundAmount: 0}, row)
      // 打开弹框状态
      self.dialogRefundFormVisible = true
      // 清除表单验证状态
      self.$nextTick(() => {
        self.$refs['dataRefundForm'].clearValidate()
      })
    },
    // 退款申请操作
    hdlRefundApply() {
      const self = this
      const {id, orderNo, refundType, remark, refundAmount} = self.dataRefundForm
      const d = {id, refundType, remark, refundAmount, refundFee: 0}
      d.refundFee = this.$u.amount.Y2F(refundAmount)

      // 效验数据格式
      self.$refs['dataRefundForm'].validate((valid) => {
        if (valid) {
          // 模态对话框组件
          self.$confirm('此操作将订单:' + orderNo + '退款申请后将不能恢复，是否继续？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 处理确认事件
            self.api.refundApply(d).then(() => {
              // 刷新数据列表
              self.hdlList()
              // 关闭弹窗状态
              self.dialogRefundFormVisible = false
              // 通知信息
              self.$u.msg('申请成功')
            })
          }).catch(() => {
          })
        }
      })
    },
    // 退款审核操作
    hdlRefund(row) {
      const self = this
      const {id, orderNo, fullRefund, refundFee} = row

      let message = '此操作将订单：' + orderNo
      // 是否全额退款
      if (fullRefund) {
        message = message + '全额退款？'
      } else {
        message = message + '部分退款？退款金额：' + this.$u.amount.F2Y(refundFee) + '元'
      }

      // 模态对话框组件
      self.$confirm(message, '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '同意',
        cancelButtonText: '拒绝',
        type: 'warning'
      }).then(() => {
        // 处理确认事件
        self.api.refund({'id': id, 'reject': false}).then(() => {
          // 刷新数据列表
          self.hdlList()
          // 通知信息
          self.$u.msg('操作成功')
        })
      }).catch(action => {
        if (action === 'cancel') {
          // 处理确认事件
          self.api.refund({'id': id, 'reject': true}).then(() => {
            // 刷新数据列表
            self.hdlList()
            // 通知信息
            self.$u.msg('操作成功')
          })
        }
      })
    },
    onKeyInput(value) {
      let payAmount = value
      // 如果输入非数字，则替换为''
      payAmount = payAmount.replace(/[^\d\.]/g, '')
      // 必须保证第一个为数字而不是.
      payAmount = payAmount.replace(/^\./g, '')
      // 保证只有出现一个.而没有多个.
      payAmount = payAmount.replace(/\.{2,}/g, '.')
      // 保证.只出现一次，而不能出现两次以上
      payAmount = payAmount.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      // 只能输入两位小数
      payAmount = payAmount.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
      // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
      if (payAmount.indexOf('.') < 0 && payAmount !== '') {
        payAmount = parseFloat(payAmount)
      }
      setTimeout(() => {
        this.dataRefundForm.refundAmount = payAmount
      }, 0)
    },
    // 格式化信息
    formatDiscInfo(json) {
      if (json) {
        const jsonArray = JSON.parse(json)
        return jsonArray.map(coupon => `使用抵扣券：${coupon.couponName}元停车满减券，券号：${coupon.couponNo}，抵扣金额：${coupon.deductionAmount}`)
      }
      return []
    }
  }
}
</script>
<style lang="scss" scoped>

.app-container {
  ::v-deep {
    .filter {
      border: 0;
    }

    .code .el-textarea.is-disabled .el-textarea__inner {
      background-color: #060606 !important;
      color: #c6c6c6 !important;
    }

    .ack .el-input {
      width: 120px;
    }
  }
}

.orderinfo {
  width: 100%;
  display: flex;
  border: 1px solid #dfe6ec;
}

.goodinfolist {
  width: 70%;
  border-right: 2px solid #dfe6ec;
}

.goodinfotitle {
  padding: 5px;
  text-align: center;
  display: flex;
  width: 100%;
  background-color: #d5dbe7;
}

.goodinfotitle span {
  width: 25%;
}

.goodinfo {
  padding: 5px;
  text-align: center;
  display: flex;
  height: 30px;
}

.goodinfo div {
  padding: 2px;
  width: 20%;
  border-bottom: 1px solid #dfe6ec;
}

.payinfolist {
  width: 30%;
}

.payinfotitle {
  padding: 5px;
  text-align: center;
  display: flex;
  width: 100%;
  background-color: #d5dbe7;
}

.payinfotitle span {
  width: 50%;
}

.payinfo {
  padding: 5px;
  text-align: center;
  display: flex;
  height: 30px;
}

.payinfo div {
  padding: 2px;
  width: 50%;
  border-bottom: 1px solid #dfe6ec;
}

</style>
